var flhMoneyVal = "0.00";
var card_id;
fee_rate = 0.00;
$(document).ready(function() {
    QueryString.Initial();
    openid = QueryString.GetValue("openid");
    initChongzhiClick();
    acct();

    $("#gotoMall").attr("href", GOMALL_URL + "?module=MERCHANT&openid=" + openid);
    $("#gotoIndex").attr("href", GETOPENID_URL + "?module=MAIN");


});

function initChongzhiClick() {
    var contentValue = $("#layerContent")[0].outerHTML.replace('style="display:none"', '').replace(/x11/g, "xx11").replace(/x12/g, "xx12").replace(/czn11/g, "cz11").replace(/mx11/g, "mm11");
    $("#chongzhi").bind("touchstart", function() {
        layer.open({
            title: [
                '个人充值'
            ],
            content: contentValue,
            btn: ['确认', '取消'],
            shadeClose: false,
            yes: function() {
                var isFillMoney = checkCZMoney();
                var isFillPassword = checkPassword();
                if (!isFillMoney || !isFillPassword) {
                    return;
                } else {
                    layer.open({
                        type: 3
                    });
                    recharge();
                }

            },
            no: function() {
                layer.closeAll();
            },
            style: 'top:20'
        });

        initLayer();
        islocking();

    });
}
// 初始化弹出框
function initLayer() {
    $(".layui-layer-content .flhye").text(flhMoneyVal);
    $(".layui-layer-content input:radio").change(function() {
        changeRechargeway();
    });

    $("#cz11").bind("input blur", function() {
        //        clearNoNum($(this)[0]);
        //        cursorEnd($(this)[0])
        var czVal = $(this).val();
        checkCZMoney();
    });
    $("#cz11").focus(function() {
        if ($("#cz11").val() == "0.00") {
            $("#cz11").val("");
        }
    })
    $("#cz11").val("0.00");
    $("#mxx11").bind("input blur", function() {
        
        checkPassword();
    })
}

// 检查充值金额是否填写
function checkCZMoney() {
    var isOk = false;
    var czinput = $("#cz11");
    var czVal = czinput.val();
    if (czVal == "0.00" || czVal == "") {
        czinput.parent().parent().next().show();
    } else {
        isOk = true;
        czinput.parent().parent().next().hide();
        czChange(czVal);
    }
    return isOk;
}

function checkPassword() {
    var mmInput = $("#mxx11");
    var ispassword = false;
    if (mmInput.val() == "") {
        mmInput.parent().parent().next().show();
    } else {
        ispassword = true;
        mmInput.parent().parent().next().hide();
    }
    return ispassword;
}

// 检查密码是否锁定
function islocking() {
    var lockUrl = PWDVARIFY_URL;
    var param = {
        openid: openid,
        action_type: 0
    }
    $.get(lockUrl, param, function(lockData) {
        if (lockData.lock_response) { // 卡被锁定
            lockRecharge();
        }
    });
}


// 余额查询
function acct() {


    var url = ACCT_URL;
    var param = {
        openid: openid
    };

    $.get(url, param, successFunction);
}

function successFunction(msg) {
    console.log("successFunction");
    console.dir(msg);

    if (msg.error_response != undefined) {
        tishiFunction(msg.error_response.sub_msg);
        return;
    }
    if (msg.acct_response.resp_code != "0000") {
        tishiFunction(msg.acct_response.resp_msg);
        return;
    }
    fee_rate = parseFloat(msg.acct_response.fee_rate);
    var tlk_card_no = "";
    // 获取通联卡号
    card_id = msg.acct_response.card_id;
    $("#spanTlkCardNo").html(card_id);
    var acct_info = msg.acct_response.acct_info_arrays.acct_info;
    var tokanflb = true; // 表没开通福利宝链接开通福利宝
    for (var i = 0; i < acct_info.length; i++) {
        info = acct_info[i];
        var info1, info3;
        if (info.acct_type == 1) {
            setTLK(info);
            info1 = jQuery.extend({}, acct_info[i]);
        } else if (info.acct_type == 2) {
            setFuliBao(info);
            tokanflb = false;
        } else if (info.acct_type == 3) {
            setGth(info);
            info3 = jQuery.extend({}, acct_info[i]);
        }
    }
    setFlhZE(info1, info3);
    if (tokanflb) {
        $("#gotoIndex").text("开通福利宝");
        $("#gotoIndex").attr("href", "index.html?openid=" + openid);
    }
}

function tishiFunction(tsContent) {
    layer.open({
        title: ['提示'],
        content: tsContent,
        btn: ['确定']
    });
}

// 设置福利户金额
function setTLK(info) {
    flhMoneyVal = info.acct_balance;
    $("#flhMoney").html(info.acct_balance);
}

// 开通福利宝的设置
function setFuliBao(info) {
    $("#flbTitle").text("福利宝账户");
    // 设置银卡号
    $("#flbxqBox .cell:last-child>.cell_ft>span");
    //银行卡号
    var card_no = String(info.card_no).replace("s", "");
    var card_no_front = card_no.substr(0, 6);
    var card_no_back = card_no.substr(card_no.length - 4, 4);
    var card_no = card_no_front + pad(card_no_back, card_no.length - 6);

    $("#money2").html(info.acct_balance);
    $("#spanCardNo").html(card_no);
    $("#flbxqBox").show();
}

// 设置总额
function setFlhZE(info1, info3) {
    if (info3) {
        money1Val = (parseFloat(info1.acct_balance) + parseFloat(info3.acct_balance)).toFixed(2);
    } else {
        money1Val = info1.acct_balance;
    }

    $("#money1").text(money1Val);
}

// 设置个体户
function setGth(info3) {
    $("#gthMoney").text(info3.acct_balance);
}


/*  ---------------充值弹窗------------------  */
// 修改充值方式
function changeRechargeway() {
    var checkedId = $(".layui-layer-content input:radio:checked").attr("id");
    if (checkedId == "xx12") {
        $(".wayCost").hide();
    } else {
        $(".wayCost").show();
    }
}

// 充值金额改变
function czChange(czVal) {

    $(".layui-layer-content .czsxf").text((czVal * fee_rate / 100).toFixed(2));
    $(".layui-layer-content .czrz").text((czVal * (100-fee_rate)/100).toFixed(2));
}

function recharge() {

    var checkedId = $(".layui-layer-content input:radio:checked").attr("id");
    var czUrl, dataType;
    var lockUrl = PWDVARIFY_URL;
    if (checkedId == "xx11") {
        czUrl = "CustRechargeFlServlet"; //福利宝方式充值接口
        dataType = "json";
    } else {
        czUrl = "CustRechargeGrServlet"; //银行卡方式充值接口
        dataType = "html";
    }
    var param = {
        openid: openid,
        action_type: 1,
        forward_url: czUrl,
        password: $("#mxx11").val(),
        cardId: card_id,
        amount: $("#cz11").val()
    }

    console.dir(param);
    $.get(lockUrl, param, function(czData) {
        console.dir(czData);
        layer.closeAll('loading');
        // 服务器错误
        if (czData.varifyerror_response != undefined || czData.error_response) {
            
            var erroeConent;
            if (czData.varifyerror_response) {
                erroeConent = czData.varifyerror_response.sub_msg;
            } else {
                erroeConent = czData.error_response.sub_msg ? czData.error_response.sub_msg : czData.error_response.msg;
            }
            layer.open({
                type: 0,
                content: erroeConent
            });
            return;
        }


        // 卡被锁定
        if (czData.lock_response != undefined) {
            lockRecharge();
            return;
        }

        // 密码错误
        if (czData.error_pwd != undefined) {
            showError("密码错误，请重新输入。")
            return;
        }



        // 支付成功
        if (checkedId == "xx11") {
            if (czData.recharge_response != undefined) {
                // 应返回充值金额传给成功页面
                location.href = "./operationResult.html?openid=" + openid;
            }
        } else {
//            window.open("./test.html");
            openNewhtml(czData);
        }

    }, dataType);
}

//  银行充值打开一个页面
function openNewhtml(htmlData) {
    document.write(htmlData);
}

// 检查是否锁定回调函数
function lockRecharge(errorValue) {
    layer.closeAll('loading');
    $("#mxx11").attr("disabled", true);
    showError("密码错误5次，请明天再试。");
}

function showError(errorValue) {
    $(".layui-layer-content .tishi:last-child>p").text(errorValue)
    $(".layui-layer-content .tishi:last-child").show();
}

// 清除"数字"和"."以外的字符
function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字而不是
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    //    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    //    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
}

